package exteditapp.state;

import exteditapp.AppletIterator;
import exteditapp.FileDefault;
import exteditapp.action.ActionEditing;

/**
 * State - edit (shows when was last modification)
 * @author Arturas Smorgn, arturas@smorgun.lt
 */
public class StateEditing extends IState {

	String label11 = " (autosave in ";
	String label12 = " seconds)";
	String label2 = "SAVE MANUALLY";
	int diff = 0;
	
	/**
	 * Default constructor
	 * @param iterator is system iterator, which performs all actions
	 * @param file this is file, which state we will hold
	 */
	public StateEditing(AppletIterator iterator, FileDefault file) {
		super(iterator, file);
		start();
	}
	public StateEditing(AppletIterator iterator, FileDefault file, boolean doRegister){
		super(iterator, file, doRegister);
		start();
	}
	
	protected void start(){
		this.setAction(new ActionEditing());
		//TODO implement start of state
	}
	
	/**
	 * Handling of new state
	 */
	public boolean handle() {
		//determine time of last save
		if(file.getFileAsObject().lastModified() != file.getLastModified()){
			file.setLastModified(file.getFileAsObject().lastModified());
			diff = this.getLifetime();
		}
		//check autosave timeout
		int some = Integer.parseInt(file.getModule().getSettings().getParameter("fileEditTimeout"));
		//count how many seconds left until autosave
		if(some > 0)
			some -= (this.getLifetime() - diff);
		//saving on save timeout
		if(some <= 0){
			this.file.setCurrentState(new StateEditingDone(this.iterator, this.file));
		}
		//autosave after specified time - no matter if it is saved consequently or not 
		else if(this.getLifetime() >= Integer.parseInt(file.getModule().getSettings().getParameter("fileAutoSaveInterval"))){
			this.file.setCurrentState(new StateEditingAutosave(this.iterator, this.file));
		}
		//display counter from last file save until save back to server
		this.getAction().setText(0, label2 + label11 + some + label12);
		return false;
	}
	
}
